<?php
declare ( strict_types = 1 );

namespace app;

use think\App;
use think\exception\HttpResponseException;
use think\facade\Db;
use think\Response;
use think\facade\Lang;


/**
 * 控制器基础类
 */
abstract class AgentRest extends BaseController
{
    //app名称
    public $_app = null;
    //控制器名称
    public $_controller = null;
    //执行方法名称
    public $_action = null;
    //method
    public $_method = 'GET';
    //query参数
    public $_param = [];
    //body参数
    public $_input = [];
    //头部
    public $_header = [];
    //头部token
    public $_token = null;
    //获取配置信息
    protected $_config = [];
    //语言信息
    public $_lang = 'zh-cn';
    //角色
    public $_role = 'guest';
    //host信息
    public $_host = null;
    //访问ip信息
    public $_ip = null;
    //用户信息
    public $_user = null;
    //唯一app标示
    public $_uniacid = '2';
    //定义检查中间件
    protected $middleware = ['app\middleware\AppInit', 'app\middleware\CheckInput' ,'think\middleware\LoadLangPack' ,'app\middleware\AutoStatic','app\middleware\StaticHour', 'app\middleware\GetAuthConfig'];
	//判断是否是微擎
	public $_is_weiqin = false;

    public function __construct ( App $app )
    {
        parent::__construct( $app );

        //获取头部信息
        $this->_header = $this->request->header();
        if (defined('IS_WEIQIN')) {
            global $_GPC, $_W;
            $this->_uniacid = $_W[ 'uniacid' ];
            $this->_user = $_W['user'];
            $role_map = [
              'founder' => 'admin',
              'operator' => 'guest',
            ];
            $this->_role = $role_map[$_W['role']] ?? 'guest';

            if (empty($this->_user)) {
                echo json_encode(['code' => 401, 'error' => '用户没有登录']);
                exit;
            }
            if (!$_W['isfounder']) {
                echo json_encode(['code' => 401, 'error' => '非超级管理员']);
                exit;
            }
            $this->_user['role_name']='admin';
        } else {
            //获取token
            if ( isset( $this->_header[ 'token' ] ) ) $this->_token = $this->_header[ 'token' ];


            //获取用户信息
            if ( !empty( $this->_token ) ) $this->_user = getUserForToken( $this->_token );
            //获取角色名称
            if ( !empty( $this->_user ) && isset( $this->_user[ 'role_name' ] ) ) $this->_role = $this->_user[ 'role_name' ];


            if ($this->_user == null) {
                echo json_encode(['code' => 401, 'error' => '用户没有登录']);
                exit;
            }

            $this->_uniacid =  !empty( $this->_user ) && isset( $this->_user[ 'uniacid' ] )  ? $this->_user[ 'uniacid' ] : -1;

//          if ($this->_user['role_name'] != 'admin') {
//              echo json_encode(['code' => 401, 'error' => '非超级管理员']);
//              exit;
//          }
        }

        //获取app名称
//      $this->_app = $this->request->app();
        $this->_app = $app->http->getName();
        //获取controller
        $this->_controller = $this->request->controller();
        //获取action名称
        $this->_action = $this->request->action();
        
        //获取method
        $this->_method = $this->request->method( true );
        //获取param
        $this->_param = $this->request->param();
        
        //获取配置信息
        $this->_config = Db::name( 'longbing_card_config' )
            ->where( [ 'uniacid' => $this->_uniacid ] )
            ->find();

        if(in_array($this->_method,['options','Options','OPTIONS'])){
            echo true;exit;
        }
        //获取body参数
        $this->_input = json_decode( $this->request->getInput(), true );

        //		//判断是否为json
        //		if(!isset($this->request->header()['Content-Type'])) {
        //			$this->_header['Content-Type'] = 'application/json';
        //			$this->app->request->withHeader($this->_header);
        //		}

        //获取该应用下面所有的uniacid
        $this->_uniacid_arr = $this->getUniacid();
        //语言
        if ( isset( $this->_header[ 'lang' ] ) ) $this->_token = $this->_header[ 'lang' ];
        //获取请求host
        $this->_host = $this->_header[ 'host' ];
        //获取访问ip
        $this->_ip = $_SERVER[ 'REMOTE_ADDR' ];
        // 控制器初始化
        $this->initialize();
        //是否是微擎
        $this->_is_weiqin = longbingIsWeiqin();
    }

    //返回请求成功的数据
    public function success ( $data, $code = 200 )
    {
        $result[ 'data' ] = $data;
        $result[ 'code' ] = $code;
        $result[ 'sign' ] = null;
        //复杂的签名
        //		if(isset($this->_user['keys'])){
        //			$result['sign'] = rsa2CreateSign($this->_user['keys'] ,json_encode($data));
        //		}
        //简单的签名
        if ( !empty( $this->_token ) ) $result[ 'sign' ] = createSimpleSign( $this->_token, is_string( $data ) ? $data : json_encode( $data ) );
        return $this->response( $result, 'json', $code  );
    }

    //返回错误数据
    public function error ( $msg, $code = 400 )
    {
//      dd($this->request);die;
//        var_dump($this->_app ,$this->_controller ,$this->_action);die;
        $result[ 'error' ] = Lang::get($msg);
        $result[ 'code' ]  = $code;
        return $this->response( $result, 'json', 200 );
    }

    /**
     * 输出返回数据
     * @access protected
     * @param mixed $data 要返回的数据
     * @param String $type 返回类型 JSON XML
     * @param integer $code HTTP状态码
     * @return Response
     */
    protected function response ( $data, $type = 'json', $code = 200 )
    {
        return Response::create( $data, $type )->code( $code );
    }

    /**
     * REST 调用
     * @access public
     * @param string $method 方法名
     * @return mixed
     * @throws \Exception
     */
    public function _empty ( $method )
    {
        if ( method_exists( $this, $method . '_' . $this->method . '_' . $this->type ) ) {
            // RESTFul方法支持
            $fun = $method . '_' . $this->method . '_' . $this->type;
        }
        elseif ( $this->method == $this->restDefaultMethod && method_exists( $this, $method . '_' . $this->type ) ) {
            $fun = $method . '_' . $this->type;
        }
        elseif ( $this->type == $this->restDefaultType && method_exists( $this, $method . '_' . $this->method ) ) {
            $fun = $method . '_' . $this->method;
        }
        if ( isset( $fun ) ) {
            return App::invokeMethod( [
                $this,
                $fun
            ]
            );
        }
        else {
            // 抛出异常
            throw new \Exception( 'error action :' . $method );
        }
    }

    /**
     * @Purpose: 获取formId
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */

    public function getFormId ( $to_uid )
    {
        // 七天前开始的的时间戳
        // $beginTime = mktime( 0, 0, 0, date( 'm' ), date( 'd' ) - 6, date( 'Y' ) );
        $beginTime = strtotime(date('Y-m-d',time()))-86400*6;
        $formId    = Db::name( 'longbing_card_formId' )
            ->where( [ 'user_id' => $to_uid ] )
            ->order( 'id desc' )
            ->select();
        if ( empty( $formId ) )
        {
            return false;
        }
        if ( $formId[ 0 ][ 'create_time' ] < $beginTime )
        {
            Db::name( 'longbing_card_formId' )
                ->where( [ 'id' => $formId[ 0 ][ 'id' ] ] )
                ->delete();
            $this->getFormId( $to_uid );
        }
        else
        {
            Db::name( 'longbing_card_formId' )
                ->where( [ 'id' => $formId[ 0 ][ 'id' ] ] )
                ->delete();
            return $formId[ 0 ][ 'formId' ];
        }
    }

    /**
     *
     * 获取支付信息
     */
    public function payConfig (){
        $pay = Db::name('longbing_card_config_pay')->where(['uniacid'=>$this->_uniacid])->find();
        if(empty($pay)){
             $this->errorMsg('no config of pay');
        }
        $setting[ 'payment' ][ 'merchant_id' ] = $pay[ 'mch_id' ];
        $setting[ 'payment' ][ 'key' ]         = $pay[ 'pay_key' ];
        $setting[ 'payment' ][ 'cert_path' ]   = $pay[ 'cert_path' ];
        $setting[ 'payment' ][ 'key_path' ]    = $pay[ 'key_path' ];
        $setting[ 'app_id' ]                   = $this->_config['appid'];
        $setting[ 'secret' ]                   = $this->_config['app_secret'];
        return $setting;
    }


    /**
     * User: chenniang
     * Date: 2019-09-12 20:37
     * @param string $msg
     * @return void
     * descption:直接抛出异常
     */
    protected function errorMsg($msg = '',$code = 400){
        $msg = Lang::get($msg);
        $this->results($msg,$code);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed  $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为0
     * @param string $type   输出类型，支持json/xml/jsonp
     * @param array  $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function results($msg, $code, array $header = [])
    {
        $result = [
            'error' => $msg,
            'code'  => $code,
        ];
        $response = Response::create($result, 'json', 200)->header($header);
        throw new HttpResponseException($response);
    }

    /**
     * @author chenniang
     * @DataTime: 2020-06-05 09:13
     * @功能说明:获取微擎的uniacid（同应用下面的）array
     */
    public function getUniacid(){

        if(defined('IS_WEIQIN')){
            //模块名字
            $app_model_name = APP_MODEL_NAME;

            $dis[]    = ['modules','like','%'.$app_model_name.'%'];
            //获取该应用下面的所有uniacid
            $uniacid  = Db::name('wxapp_versions')->where($dis)->column('uniacid');
        }else{

            $uniacid  = [$this->_user['uniacid']];
        }
        return $uniacid;
    }
}
